/**
 * @description 表单弹窗通用
 * */
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    opId: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      title: '',
      submitFunc: null
    }
  },
  methods: {
    close(flag = false) {
      if (this.visible) {
        this.$emit('close', flag)
        this.$refs.postForm && this.$refs.postForm.resetFields()
      }
    },
    async open() {
      if (this.opId || this.isEdit) {
        this.title = '更新'
        this.submitFunc = this.editFunc
        await this.getDetail()
      } else {
        this.title = '新增'
        this.submitFunc = this.addFunc
      }
    },
    submit() {
      this.$refs.postForm.validate(async(valid) => {
        if (valid) {
          const temp = { ...this.postData }
          if (this.opId) {
            temp.id = this.opId
          }
          const { success, message } = await this.submitFunc(temp)
          if (success) {
            this.$message({ type: 'success', message: '操作成功' })
            this.close(true)
          } else {
            this.$message({ type: 'error', message })
          }
        }
      })
    },
    async getDetail() {
      const { data, success, message } = await this.detailFunc(this.opId)
      if (success) {
        for (const key in this.postData) {
          if (data[key] && data[key] !== '') {
            this.postData[key] = data[key]
          }
        }
      } else {
        this.$message({ type: 'error', message })
      }
    }
  }
}
